
<template>
  <div class="statistics-container snapshot-page">
    <div class="page-header">
      <el-form :inline="true" size="small" class="filter-form">
        <el-form-item label="主机">
          <el-select
            v-model="selectedHost"
            placeholder="请选择主机"
            value-key="device_id"
            style="width: 260px"
            filterable
            clearable
            @change="handleHostChange"
          >
            <el-option
              v-for="item in hostOptions"
              :key="item.device_id"
              :label="item.device_name || item.device_id"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="时间范围">
          <el-radio-group v-model="filters.scope" @change="handleScopeChange">
            <el-radio-button label="today">今日</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="year">本年度</el-radio-button>
            <el-radio-button label="custom">选择日期</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="filters.scope === 'custom'">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :default-time="['00:00:00', '23:59:59']"
            range-separator="至"
            @change="handleDateRangeChange"
            style="width: 360px"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="date-text">{{ dateLabel }}</div>

    <div class="snapshot-content">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-card shadow="never" class="stat-card" v-loading="loading.stats">
            <div class="stat-items">
              <div class="stat-item" v-for="card in statHighlightsList" :key="card.label">
                <p class="stat-title">{{ card.label }}</p>
                <p class="stat-value">{{ card.text || '--' }}</p>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="24">
          <el-card shadow="never" class="chart-card" v-loading="loading.trend">
            <div class="card-header">
<!--              <span>主机温度趋势</span>-->
            </div>
            <div class="trend-chart" ref="trendChart"></div>
          </el-card>
        </el-col>

        <el-col :span="24">
          <el-card shadow="never" class="table-card">
<!--            <div class="card-header">
              <span>主机温度与电参台账</span>
            </div>-->
            <el-table
              v-loading="loading.table"
              :data="snapshotList"
              border
              stripe
              height="480"
            >
              <el-table-column label="序号" width="70" align="center">
                <template slot-scope="scope">
                  {{ (filters.pageNum - 1) * filters.pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="时间" prop="time" min-width="180">
                <template slot-scope="scope">{{ formatTime(scope.row.time) }}</template>
              </el-table-column>
              <el-table-column label="AB线电压(kV)" prop="uab" min-width="110" />
              <el-table-column label="BC线电压(kV)" prop="ubc" min-width="110" />
              <el-table-column label="CA线电压(kV)" prop="uca" min-width="110" />
              <el-table-column label="A相电流(A)" prop="ia" min-width="90" />
              <el-table-column label="B相电流(A)" prop="ib" min-width="90" />
              <el-table-column label="C相电流(A)" prop="ic" min-width="90" />
              <el-table-column label="有功功率(kW)" prop="p" min-width="110" />
              <el-table-column label="无功功率(kVar)" prop="q" min-width="110" />
              <el-table-column label="频率(Hz)" prop="f" min-width="100" />
              <el-table-column
                v-for="field in temperatureFields"
                :key="field.key"
                :label="field.label"
                :prop="field.key"
                min-width="130"
              />
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="filters.pageNum"
              :limit.sync="filters.pageSize"
              @pagination="handlePagination"
            />
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import Pagination from '@/components/Pagination'
import { parseTime } from '@/utils/ruoyi'
import {
  fetchHostDevices,
  fetchDeviceSnapshots,
  fetchTemperatureStats,
  fetchTemperatureTrend
} from '@/views/statistics/api/hostDeviceSnapshotApi'

const TEMPERATURE_FIELDS = [
  { key: 'astatortemp1', label: '定子A相温度1' },
  { key: 'bstatortemp1', label: '定子B相温度1' },
  { key: 'cstatortemp1', label: '定子C相温度1' },
  { key: 'astatortemp2', label: '定子A相温度2' },
  { key: 'bstatortemp2', label: '定子B相温度2' },
  { key: 'cstatortemp2', label: '定子C相温度2' },
  { key: 'nonshaftendtemp', label: '非轴伸端温度' },
  { key: 'shaftendtemp', label: '轴伸端温度' }
]

export default {
  name: 'DeviceTemperatureSnapshot',
  components: { Pagination },
  data() {
    return {
      hostOptions: [],
      selectedHost: null,
      filters: {
        scope: 'month',
        pageNum: 1,
        pageSize: 10
      },
      dateRange: [],
      temperatureFields: TEMPERATURE_FIELDS,
      temperatureStats: [],
      trendData: [],
      snapshotList: [],
      total: 0,
      loading: {
        stats: false,
        trend: false,
        table: false
      },
      chart: null
    }
  },
  computed: {
    effectiveScope() {
      return this.filters.scope === 'custom' ? 'month' : this.filters.scope
    },
    dateLabel() {
      const now = new Date()
      const y = now.getFullYear()
      const m = now.getMonth() + 1
      const d = now.getDate()
      if (this.filters.scope === 'today') {
        return `${y}年${m}月${d}日`
      }
      if (this.filters.scope === 'year') {
        return `${y}年`
      }
      return `${y}年${m}月`
    },
    statHighlightsList() {
      const grouped = new Map()
      this.temperatureStats.forEach(item => {
        const label = item.statLabel || item.statType || ''
        if (!grouped.has(label)) {
          grouped.set(label, [])
        }
        grouped.get(label).push(item)
      })
      const order = ['最高温度', '最低温度', '平均温度']
      const result = []
      const parseValue = value => {
        const num = Number(value)
        return Number.isFinite(num) ? num : null
      }
      const pickItem = (items, mode) => {
        if (!items || items.length === 0) {
          return null
        }
        if (mode === 'max' || mode === 'min') {
          const comparator = mode === 'max'
            ? (curr, best) => curr > best
            : (curr, best) => curr < best
          let chosen = null
          let chosenVal = null
          items.forEach(item => {
            const val = parseValue(item.value)
            if (val === null) {
              if (!chosen) {
                chosen = item
              }
              return
            }
            if (chosen === null || chosenVal === null || comparator(val, chosenVal)) {
              chosen = item
              chosenVal = val
            }
          })
          return chosen || items[0]
        }
        return items[0]
      }
      order.forEach(label => {
        if (grouped.has(label)) {
          const items = grouped.get(label)
          let mode = 'default'
          if (label.indexOf('最高') !== -1) {
            mode = 'max'
          } else if (label.indexOf('最低') !== -1) {
            mode = 'min'
          }
          const target = pickItem(items, mode)
          result.push({ label, text: target?.text || '' })
          grouped.delete(label)
        }
      })
      grouped.forEach((items, label) => {
        const target = items[0]
        result.push({ label, text: target?.text || '' })
      })
      return result
    },
    timeParams() {
      if (this.filters.scope === 'custom' && Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        return {
          startTime: this.dateRange[0],
          endTime: this.dateRange[1]
        }
      }
      return {}
    }
  },
  created() {
    this.fetchHostOptions()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    async fetchHostOptions() {
      try {
        const res = await fetchHostDevices()
        if (res.code === 200 && Array.isArray(res.data)) {
          this.hostOptions = res.data
          if (this.hostOptions.length > 0) {
            this.selectedHost = this.hostOptions[0]
            this.handleQuery()
            window.addEventListener('resize', this.handleResize)
          }
        }
      } catch (error) {
        console.error('获取主机列表失败', error)
      }
    },
    handleHostChange() {
      if (this.selectedHost) {
        this.handleQuery()
      }
    },
    handleScopeChange(value) {
      if (value !== 'custom') {
        this.dateRange = []
        this.handleQuery()
      }
    },
    handleDateRangeChange(value) {
      this.dateRange = value || []
    },
    handleQuery() {
      if (!this.selectedHost) {
        this.$message.warning('请先选择主机')
        return
      }
      if (this.filters.scope === 'custom') {
        if (!this.dateRange || this.dateRange.length !== 2) {
          this.$message.warning('请选择自定义时间范围')
          return
        }
      }
      this.filters.pageNum = 1
      this.loadStats()
      this.loadTrend()
      this.loadSnapshots()
    },
    handleReset() {
      this.filters.scope = 'month'
      this.dateRange = []
      this.filters.pageNum = 1
      this.filters.pageSize = 10
      if (this.selectedHost) {
        this.handleQuery()
      }
    },
    async loadStats() {
      this.loading.stats = true
      try {
        const params = {
          deviceId: this.selectedHost.device_id,
          scope: this.effectiveScope,
          ...this.timeParams
        }
        const res = await fetchTemperatureStats(params)
        const items = res.code === 200 ? (res.data?.items || []) : []
        this.temperatureStats = items
      } catch (error) {
        console.error('获取温度统计失败', error)
        this.temperatureStats = []
      } finally {
        this.loading.stats = false
      }
    },
    async loadTrend() {
      this.loading.trend = true
      try {
        const params = {
          deviceId: this.selectedHost.device_id,
          scope: this.effectiveScope,
          ...this.timeParams
        }
        const res = await fetchTemperatureTrend(params)
        this.trendData = res.code === 200 ? (res.data?.items || []) : []
        this.renderTrendChart()
      } catch (error) {
        console.error('获取温度趋势失败', error)
        this.trendData = []
        this.renderTrendChart()
      } finally {
        this.loading.trend = false
      }
    },
    async loadSnapshots() {
      this.loading.table = true
      try {
        const params = {
          deviceKgId: this.selectedHost.device_kg_id,
          scope: this.effectiveScope,
          pageNum: this.filters.pageNum,
          pageSize: this.filters.pageSize,
          ...this.timeParams
        }
        const res = await fetchDeviceSnapshots(params)
        const data = res.code === 200 ? res.data || {} : {}
        this.snapshotList = data.records || []
        this.total = data.total || 0
      } catch (error) {
        console.error('获取台账失败', error)
        this.snapshotList = []
        this.total = 0
      } finally {
        this.loading.table = false
      }
    },
    renderTrendChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.trendChart)
      }
      const xAxisData = this.trendData.map(item => item.label)
      const series = this.temperatureFields.map(field => ({
        name: field.label,
        type: 'line',
        smooth: true,
        showSymbol: false,
        data: this.trendData.map(item => (item.values ? item.values[field.key] : null))
      }))
      const option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.temperatureFields.map(item => item.label)
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value',
          name: '温度(℃)'
        },
        series
      }
      this.chart.setOption(option, true)
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },
    handlePagination({ page, limit }) {
      this.filters.pageNum = page
      this.filters.pageSize = limit
      this.loadSnapshots()
    },
    formatTime(value) {
      return value ? parseTime(value) : '-'
    }
  }
}
</script>

<style lang="scss" scoped>
.snapshot-page {
  .filter-form {
    background: #fff;
    padding: 16px;
    border-radius: 8px;
  }

  .stat-card {
    margin-bottom: 20px;
    .stat-items {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
    }
    .stat-item {
      flex: 1;
      min-width: 220px;
      padding: 12px 18px;
      border-right: 1px solid #f0f0f0;
      &:last-child {
        border-right: none;
      }
      .stat-title {
        font-size: 18px;
        color: #303133;
        font-weight: 600;
        margin-bottom: 6px;
      }
      .stat-value {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;
    .card-header {
      font-weight: 600;
      margin-bottom: 12px;
    }
    .trend-chart {
      width: 100%;
      height: 360px;
    }
  }

  .table-card {
    .card-header {
      font-weight: 600;
      margin-bottom: 12px;
    }
  }

  .date-text {
    text-align: center;
    font-weight: 700;
    font-size: 18px;
    color: #303133;
    margin: 12px 0 18px;
  }
}
</style>
